using CoreManager.API.Common;
using CoreManager.MessageQueue.Models;
using CoreManager.MessageQueue.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace CoreManager.API.System.Controllers;

/// <summary>
/// Kafka消息队列控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
[AllowAnonymous]
public class KafkaController : BaseController
{
    private readonly IKafkaProducerService _producerService;
    private readonly KafkaOptions _kafkaOptions;

    public KafkaController(
        IKafkaProducerService producerService, 
        IOptions<KafkaOptions> kafkaOptions,
        ILogger<KafkaController> logger) : base(logger)
    {
        _producerService = producerService;
        _kafkaOptions = kafkaOptions.Value;
    }

    /// <summary>
    /// 发送消息到指定主题
    /// </summary>
    /// <param name="request">发送消息请求</param>
    /// <returns>发送结果</returns>
    [HttpPost("send")]
    public async Task<IActionResult> SendMessage([FromBody] SendMessageRequest request)
    {
        try
        {
            if (string.IsNullOrEmpty(request.Topic))
            {
                return BadRequest("主题不能为空");
            }

            var message = new KafkaMessage
            {
                MessageType = request.MessageType ?? "DefaultMessage",
                Data = request.Data,
                Source = "CoreManager.API"
            };

            var result = await _producerService.SendMessageAsync(request.Topic, message, request.Key);

            Logger.LogInformation("Message sent to topic {Topic}, result: {IsSuccess}", request.Topic, result.IsSuccess);

            return result.IsSuccess 
                ? Success(result, "消息发送成功") 
                : Fail(result.ErrorMessage ?? "消息发送失败", 500);
        }
        catch (Exception ex)
        {
            return HandleException(ex, $"发送消息到主题 {request.Topic}");
        }
    }

    /// <summary>
    /// 批量发送消息
    /// </summary>
    /// <param name="request">批量发送消息请求</param>
    /// <returns>发送结果列表</returns>
    [HttpPost("send-batch")]
    public async Task<IActionResult> SendBatchMessages([FromBody] SendBatchMessageRequest request)
    {
        try
        {
            if (string.IsNullOrEmpty(request.Topic))
            {
                return BadRequest("主题不能为空");
            }

            if (request.Messages == null || !request.Messages.Any())
            {
                return BadRequest("消息列表不能为空");
            }

            var kafkaMessages = request.Messages.Select(msg => new KafkaMessage
            {
                MessageType = msg.MessageType ?? "DefaultMessage",
                Data = msg.Data,
                Source = "CoreManager.API"
            }).ToList();

            var results = await _producerService.SendMessagesAsync(request.Topic, kafkaMessages);

            Logger.LogInformation("Batch messages sent to topic {Topic}, count: {Count}", request.Topic, results.Count);

            var successCount = results.Count(r => r.IsSuccess);
            var failCount = results.Count - successCount;

            return Success(results, $"批量消息发送完成，成功: {successCount}，失败: {failCount}");
        }
        catch (Exception ex)
        {
            return HandleException(ex, $"批量发送消息到主题 {request.Topic}");
        }
    }

    /// <summary>
    /// 发送系统事件消息
    /// </summary>
    /// <param name="request">系统事件请求</param>
    /// <returns>发送结果</returns>
    [HttpPost("send-system-event")]
    public async Task<IActionResult> SendSystemEvent([FromBody] SystemEventRequest request)
    {
        try
        {
            var eventData = new
            {
                EventType = request.EventType,
                EventTime = DateTime.UtcNow,
                UserId = GetCurrentUserId(),
                UserName = GetCurrentUserName(),
                Description = request.Description,
                Data = request.Data
            };

            var result = await _producerService.SendMessageAsync(_kafkaOptions.Topics.SystemEvents, eventData, request.EventType);

            Logger.LogInformation("System event sent: {EventType}, result: {IsSuccess}", request.EventType, result.IsSuccess);

            return result.IsSuccess 
                ? Success(result, "系统事件发送成功") 
                : Fail(result.ErrorMessage ?? "系统事件发送失败", 500);
        }
        catch (Exception ex)
        {
            return HandleException(ex, $"发送系统事件 {request.EventType}");
        }
    }

    /// <summary>
    /// 发送用户活动消息
    /// </summary>
    /// <param name="request">用户活动请求</param>
    /// <returns>发送结果</returns>
    [HttpPost("send-user-activity")]
    public async Task<IActionResult> SendUserActivity([FromBody] UserActivityRequest request)
    {
        try
        {
            var activityData = new
            {
                ActivityType = request.ActivityType,
                ActivityTime = DateTime.UtcNow,
                UserId = GetCurrentUserId(),
                UserName = GetCurrentUserName(),
                IP = GetClientIP(),
                UserAgent = Request.Headers["User-Agent"].ToString(),
                Description = request.Description,
                Data = request.Data
            };

            var result = await _producerService.SendMessageAsync(_kafkaOptions.Topics.UserActivities, activityData);

            Logger.LogInformation("User activity sent: {ActivityType}, user: {UserId}", request.ActivityType, GetCurrentUserId());

            return result.IsSuccess 
                ? Success(result, "用户活动消息发送成功") 
                : Fail(result.ErrorMessage ?? "用户活动消息发送失败", 500);
        }
        catch (Exception ex)
        {
            return HandleException(ex, $"发送用户活动 {request.ActivityType}");
        }
    }

    /// <summary>
    /// 测试Kafka连接
    /// </summary>
    /// <returns>连接状态</returns>
    [HttpGet("test-connection")]
    public IActionResult TestConnection()
    {
        try
        {
            // 这里可以添加实际的连接测试逻辑
            var testResult = new
            {
                Status = "Connected",
                Timestamp = DateTime.UtcNow,
                Message = "Kafka连接正常",
                BootstrapServers = _kafkaOptions.BootstrapServers
            };

            return Success(testResult, "连接测试成功");
        }
        catch (Exception ex)
        {
            return HandleException(ex, "测试Kafka连接");
        }
    }

    /// <summary>
    /// 获取所有配置的主题
    /// </summary>
    /// <returns>主题列表</returns>
    [HttpGet("topics")]
    public IActionResult GetTopics()
    {
        try
        {
            var topicInfo = new
            {
                CoreManagerEvents = _kafkaOptions.Topics.CoreManagerEvents,
                SystemNotifications = _kafkaOptions.Topics.SystemNotifications,
                UserActivities = _kafkaOptions.Topics.UserActivities,
                SystemEvents = _kafkaOptions.Topics.SystemEvents,
                CustomTopics = _kafkaOptions.Topics.CustomTopics,
                AllSubscriptionTopics = _kafkaOptions.Topics.GetAllSubscriptionTopics()
            };

            return Success(topicInfo, "获取主题配置成功");
        }
        catch (Exception ex)
        {
            return HandleException(ex, "获取主题配置");
        }
    }

    /// <summary>
    /// 获取客户端IP地址
    /// </summary>
    /// <returns></returns>
    private string GetClientIP()
    {
        var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
        if (string.IsNullOrEmpty(ip))
        {
            ip = Request.Headers["X-Forwarded-For"].FirstOrDefault() ?? "Unknown";
        }
        return ip;
    }
}

/// <summary>
/// 发送消息请求
/// </summary>
public class SendMessageRequest
{
    /// <summary>
    /// 主题名称
    /// </summary>
    public string Topic { get; set; } = string.Empty;

    /// <summary>
    /// 消息类型
    /// </summary>
    public string? MessageType { get; set; }

    /// <summary>
    /// 消息键
    /// </summary>
    public string? Key { get; set; }

    /// <summary>
    /// 消息数据
    /// </summary>
    public object? Data { get; set; }
}

/// <summary>
/// 批量发送消息请求
/// </summary>
public class SendBatchMessageRequest
{
    /// <summary>
    /// 主题名称
    /// </summary>
    public string Topic { get; set; } = string.Empty;

    /// <summary>
    /// 消息列表
    /// </summary>
    public List<MessageData> Messages { get; set; } = new();
}

/// <summary>
/// 消息数据
/// </summary>
public class MessageData
{
    /// <summary>
    /// 消息类型
    /// </summary>
    public string? MessageType { get; set; }

    /// <summary>
    /// 消息数据
    /// </summary>
    public object? Data { get; set; }
}

/// <summary>
/// 系统事件请求
/// </summary>
public class SystemEventRequest
{
    /// <summary>
    /// 事件类型
    /// </summary>
    public string EventType { get; set; } = string.Empty;

    /// <summary>
    /// 事件描述
    /// </summary>
    public string? Description { get; set; }

    /// <summary>
    /// 事件数据
    /// </summary>
    public object? Data { get; set; }
}

/// <summary>
/// 用户活动请求
/// </summary>
public class UserActivityRequest
{
    /// <summary>
    /// 活动类型
    /// </summary>
    public string ActivityType { get; set; } = string.Empty;

    /// <summary>
    /// 活动描述
    /// </summary>
    public string? Description { get; set; }

    /// <summary>
    /// 活动数据
    /// </summary>
    public object? Data { get; set; }
}
